using FastDevTemplate.Common.Util;
using FastDevTemplate.DataAccess.Base;
using FastDevTemplate.Service.Interface.Base;
using Microsoft.EntityFrameworkCore;

namespace FastDevTemplate.Service.Base;

public class GuidAuditCurdService<TEntity, TEntityResultDto, TEntityGetDto, TAddEntityDto, TUpdateEntityDto>(
    DbContext dbContext) :
    AuditCurdService<TEntity, Guid, TEntityResultDto, TEntityGetDto, TAddEntityDto, TUpdateEntityDto>(dbContext)
    where TEntity : AuditEntity<Guid>, new()
    where TEntityResultDto : class
    where TEntityGetDto : class
    where TAddEntityDto : class
    where TUpdateEntityDto : class
{
    public override Guid GenerateKey(TEntity entity)
    {
        entity.ID = Guid.NewGuid();
        return entity.ID;
    }
}
    

public abstract class AuditCurdService<TEntity, TKey, TEntityResultDto, TEntityGetDto, TAddEntityDto, TUpdateEntityDto>(
    DbContext dbContext):
    BaseCurdService<TEntity, TKey, TEntityResultDto, TEntityGetDto, TAddEntityDto, TUpdateEntityDto>(dbContext), 
    IAuditCurdService<TEntity, TKey, TEntityResultDto, TEntityGetDto, TAddEntityDto, TUpdateEntityDto> 
    where TEntity : AuditEntity<TKey>, new()
    where TEntityResultDto : class
    where TEntityGetDto : class
    where TAddEntityDto : class
    where TUpdateEntityDto : class
{

    public int Recover(TKey id)
    {
        return RecoverAsync(id).Result;
    }
    public async Task<int> RecoverAsync(TKey id)
    {
        var user = await DbSet.FindAsync(id);
        if (user == null)
            return ErrorHandling(ErrorType.LogicNotFindEntityError, nameof(RecoverAsync));
        user.ToUndeleteState();

        try
        {
            var count = await Dao.SaveChangesAsync();
            return count > 0 ? count : ErrorHandling(ErrorType.DataBaseSaveError, nameof(RecoverAsync));
        }

        catch (Exception e)
        {
            return ErrorHandling(ErrorType.DataBaseSaveError, e);
        }
    }
}